package com.situ.mall.notification.api.api;


import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.mall.common.util.JsonResult;
import com.situ.mall.notification.api.service.UserFeignService;
import com.situ.mall.notification.spi.model.DTO.OrderStatusDTO;
import com.situ.mall.notification.spi.model.DTO.PriceChangeDTO;
import com.situ.mall.notification.spi.model.DTO.SecurityAlertDTO;
import com.situ.mall.notification.spi.model.DTO.SystemAlertDTO;
import com.situ.mall.notification.spi.model.Notification;
import com.situ.mall.notification.spi.service.NotificationService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.time.LocalDateTime;
import java.util.List;
import java.util.Objects;

@RestController
@RequestMapping(value = "/api/notifications" ,produces = MediaType.APPLICATION_JSON_VALUE)
public class NotificationApi {

    private NotificationService notificationService;

    private UserFeignService userFeignService;

    @Autowired
    public void setUserFeignService(UserFeignService userFeignService) {
        this.userFeignService = userFeignService;
    }

    @Autowired
    public void setNotificationService(NotificationService notificationService) {
        this.notificationService = notificationService;
    }

    @GetMapping("/findAll")
    public ResponseEntity<JsonResult<?>> findAll(@RequestParam Integer pageNo,
                                                 @RequestParam Integer pageSize,
                                                 Notification notification){

        Page<Notification> page = new Page<>(pageNo, pageSize);
        Page<Notification> all = notificationService.findAll(page, notification);
        return ResponseEntity.ok(JsonResult.success(all));
    }
    @GetMapping("/findById")
    public ResponseEntity<JsonResult<?>> findById(@RequestParam Integer id){
        Notification notification = notificationService.findById(id);
        return ResponseEntity.ok(JsonResult.success(notification));
    }

    @PostMapping("/save")
    public ResponseEntity<JsonResult<?>> save(@RequestBody Notification notification){
        boolean save = notificationService.save(notification);
        if (!save){
            return ResponseEntity.ok(JsonResult.fail("保存失败"));
        }
        return ResponseEntity.ok(JsonResult.success(save));
    }

    @PutMapping("/update")
    public ResponseEntity<JsonResult<?>> update(@RequestBody Notification notification){
        boolean update = notificationService.update(notification);
        if (!update){
            return ResponseEntity.ok(JsonResult.fail("更新失败"));
        }
        return ResponseEntity.ok(JsonResult.success(update));
    }

    @DeleteMapping("/deleteByIds")
    public ResponseEntity<JsonResult<?>> deleteByIds(@RequestBody List<Integer> ids){
        int delete = notificationService.deleteByIds(ids);
        if (delete>0){
            return ResponseEntity.ok(JsonResult.success(delete));
        }else {
            return ResponseEntity.ok(JsonResult.fail("删除失败"));
        }
    }

    @PostMapping("/orderStatusChange")
    public ResponseEntity<JsonResult<?>> OrderStatusChange(@RequestBody OrderStatusDTO dto){
        try{
            Notification notification=new Notification();
            notification.setUserId(dto.getUserId());//用户id
            notification.setTitle("订单状态变更提醒");//标题
            notification.setContent(String.format("您的订单[%d]状态已从[%s]变更为[%s]",
                    dto.getOrderId(), dto.getOldStatus(), dto.getNewStatus()));//具体内容
            notification.setType(2);//2订单通知
            notification.setLevel(2);//程度：2重要
            notification.setRelatedId(dto.getOrderId());//关联id
            notification.setRelatedType("order");//关联类型 订单
            notification.setCreatedTime(LocalDateTime.now());//创建时间
            notification.setUpdatedTime(LocalDateTime.now());//修改时间
            boolean success = notificationService.save(notification);
            if (success){
                return ResponseEntity.ok(JsonResult.success("订单状态变更通知成功"));
            }else {
                return ResponseEntity.ok(JsonResult.fail("订单状态变更通知失败"));
            }
        }catch (Exception e){
            return ResponseEntity.ok(JsonResult.fail("订单状态变更通知出现异常"+e.getMessage()));
        }
    }

    @PostMapping("/priceChange")
    public ResponseEntity<JsonResult<?>> PriceChange(@RequestBody PriceChangeDTO dto){
        try{
            Notification notification=new Notification();
            notification.setTitle("商品价格变动提醒");//标题
            notification.setContent(String.format("您关注的商品[%s]价格已从[%.2f]调整为[%.2f]",
                    dto.getProductName(), dto.getOldPrice(), dto.getNewPrice()));//具体内容
            notification.setType(2);//2订单通知
            notification.setLevel(2);//程度：2重要
            notification.setRelatedId(dto.getProductId());//关联id
            notification.setRelatedType("product");//关联类型 订单
            notification.setCreatedTime(LocalDateTime.now());//创建时间
            notification.setUpdatedTime(LocalDateTime.now());//修改时间
            int count=0;

            boolean success=true;
            for (int i:dto.getIds()){
                notification.setUserId(i);
                success=notificationService.save(notification);
                if (success){
                    count++;
                }
            }
            if (count==dto.getIds().length){
                return ResponseEntity.ok(JsonResult.success("商品价格变动通知成功"));
            }else {
                return ResponseEntity.ok(JsonResult.fail("商品价格变动通知失败"));
            }
        }catch (Exception e){
            return ResponseEntity.ok(JsonResult.fail("商品价格变动出现异常："+e.getMessage()));
        }
    }

    @PostMapping("/securityAlert")
    public ResponseEntity<JsonResult<?>> securityAlert(@RequestBody SecurityAlertDTO dto){
        try{
            Notification notification=new Notification();
            notification.setUserId(dto.getUserId());
            notification.setTitle("安全提醒 - " + dto.getAlertType());
            notification.setContent(String.format("检测到%s: %s。操作时间：%s，IP地址：%s。建议操作：%s",
                    dto.getAlertType(), dto.getDescription(), dto.getActionTime(),
                    dto.getIpAddress(), dto.getRecommendedAction()));

            int level = switch (dto.getAlertLevel()) {
                case "普通" -> 1;
                case "重要" -> 2;
                case "紧急" -> 3;
                default -> 1;
            };//数据库默认是1
            notification.setLevel(level);
            notification.setType(4);//安全通知
            notification.setCreatedTime(LocalDateTime.now());
            notification.setUpdatedTime(LocalDateTime.now());

            boolean success=notificationService.save(notification);
            if (success){
                return ResponseEntity.ok(JsonResult.success("安全警报通知成功"));
            }else {
                return ResponseEntity.ok(JsonResult.fail("安全警报通知失败"));
            }
        }catch (Exception e){
            return ResponseEntity.ok(JsonResult.fail("商品价格变动出现异常："+e.getMessage()));
        }
    }

    @PostMapping("/systemAlert")
    public ResponseEntity<JsonResult<?>> systemAlert(@RequestBody SystemAlertDTO dto){
        try{
            Notification notification=new Notification();
             // 系统通知可能是全局的，不特定于某个用户
            notification.setTitle(dto.getTitle());
            notification.setContent(dto.getContent());
            notification.setType(1); // 系统通知类型
            notification.setLevel(dto.getLevel());
            notification.setRelatedType("system");
            notification.setCreatedTime(LocalDateTime.now());
            notification.setUpdatedTime(LocalDateTime.now());
            ResponseEntity<JsonResult<?>> alertUsers = userFeignService.getAlertUsers(dto.getTargetType());
            int[] ids= (int[]) Objects.requireNonNull(alertUsers.getBody()).getData();
            boolean success=true;
            int count=0;
            for (int i:ids){
                notification.setUserId(i);
                success=notificationService.save(notification);
                if (success){
                    count++;
                }
            }
            if (count==ids.length){
                return ResponseEntity.ok(JsonResult.success("系统通知发送成功"));
            }else {
                return ResponseEntity.ok(JsonResult.fail("系统通知发送失败"));
            }
        }catch (Exception e){
            return  ResponseEntity.ok(JsonResult.fail("系统通知出现异常:"+e.getMessage()));
        }
    }

    // 用户端通知相关接口
    @GetMapping("/user")
    public ResponseEntity<JsonResult<?>> getUserNotifications(@RequestParam Integer pageNo,
                                                            @RequestParam Integer pageSize,
                                                            @RequestParam Integer userId) {
        Page<Notification> page = new Page<>(pageNo, pageSize);
        Page<Notification> userNotifications = notificationService.findUserNotifications(page, userId);
        return ResponseEntity.ok(JsonResult.success(userNotifications));
    }

    @GetMapping("/unread/count")
    public ResponseEntity<JsonResult<?>> getUnreadNotificationCount(@RequestParam Integer userId) {
        Integer count = notificationService.getUnreadNotificationCount(userId);
        return ResponseEntity.ok(JsonResult.success(count));
    }

    @PutMapping("/{id}/read")
    public ResponseEntity<JsonResult<?>> markNotificationAsRead(@PathVariable Integer id) {
        boolean success = notificationService.markNotificationAsRead(id);
        if (success) {
            return ResponseEntity.ok(JsonResult.success("标记成功"));
        } else {
            return ResponseEntity.ok(JsonResult.fail("标记失败"));
        }
    }

    @PutMapping("/readAll")
    public ResponseEntity<JsonResult<?>> markAllNotificationsAsRead(@RequestParam Integer userId) {
        boolean success = notificationService.markAllNotificationsAsRead(userId);
        if (success) {
            return ResponseEntity.ok(JsonResult.success("全部标记成功"));
        } else {
            return ResponseEntity.ok(JsonResult.fail("标记失败"));
        }
    }

}
